package atm.service.Impl;

import atm.dao.BaseDAO;
import atm.dao.UserDAO;
import atm.pojo.UserDO;
import atm.dao.impl.UserDAOImpl;
import atm.service.UserService;


public class UserServiceImpl  implements UserService {
    private UserDAO userDAO = new UserDAOImpl();


    @Override
    public UserDO getByUserAccountAndPassword(String userAccount, String password) {
        return userDAO.getByUsernameAndPwd(userAccount, password);
    }

    @Override
    public void saveMoney(int id, double blance) {
        UserDO user = userDAO.getById(id);
        user.setBalance(user.getBalance() + blance);
        userDAO.update(user);
    }

    @Override
    public void takeMoney(int id, double balance) throws Exception {

    }


    public void getMoney(int id, double blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getBalance() < blance) {
            throw new Exception("余额不足");
        }
        user.setBalance(user.getBalance() - blance);
        userDAO.update(user);
    }

    @Override
    public void changePassword(String oldPwd, String newPwd, int id) throws Exception {
        UserDO users = userDAO.getById(id);//本人账户
        if (!oldPwd.equals(users.getPassword())) {
            throw new Exception("密码输入错误");
        }
        if (oldPwd.equals(newPwd)) {
            throw new Exception("新旧密码不能一致");
        }
        users.setPassword(newPwd);
        userDAO.update(users);
    }


    @Override
    public void transfer(String otherName, double blance, int id) throws Exception {
        UserDO otherUsers = userDAO.getByName(otherName);//转账给的那个人的账户
        UserDO users = userDAO.getById(id);//本人账户
        if (users.getBalance() < blance) {
            throw new Exception("当前账户余额不足");
        }
        if (otherUsers == null) {
            throw new Exception("查无此人");
        }
        if (otherUsers.getAccount().equals(users.getAccount())) {
            throw new Exception("不能转账给自己");
        }
        users.setBalance(users.getBalance() - blance);
        otherUsers.setBalance(otherUsers.getBalance() + blance);
        userDAO.update(users, otherUsers);

    }
}
